package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.assistant.common.enums.ExcelTypeEnum;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.*;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.ExcelIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.bifang.module.system.core.dao.model.ExcelModel;
import com.bifang.module.system.core.dao.model.ExcelParam;
import com.bifang.module.system.core.dao.service.ExcelModelService;
import com.bifang.module.system.core.dao.service.ExcelParamService;
import com.bifang.module.system.core.dao.service.SysDictService;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.EduSchoolConfigExcelSaveVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.EduSchoolConfigVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.SchoolConfigFileVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.SchoolConfigSaveVO;
import com.jwsoft.manager.common.vo.eduSchoolVacancy.EduSchoolVacancyQueryVO;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.model.EduSchoolConfig;
import com.jwsoft.manager.core.dao.service.EduAreaService;
import com.jwsoft.manager.core.dao.service.EduSchoolConfigService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.dao.service.EduSchoolVacancyService;
import com.jwsoft.manager.core.integration.EduSchoolConfigJhIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 所属学校配置表业务实现类
 *
 * @author hhj
 * @since 2022-12-21
 */
@ApiService(funcCode = "eduSchoolConfigJh", title = "学校招生计划管理")
public class EduSchoolConfigJhIntegrationImpl implements EduSchoolConfigJhIntegration {

    @Autowired
    public EduSchoolConfigService eduSchoolConfigService;
    @Autowired
    public DictHelper dictHelper;

    @Autowired
    public OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    public EduSystemConfigIntegration eduSystemConfigIntegration;

    @Autowired
    public EduHelper eduHelper;

    @Autowired
    public EduSchoolVacancyService eduSchoolVacancyService;

    @Autowired
    public EduAreaService eduAreaService;

    @Autowired
    public EduSchoolService eduSchoolService;

    @Autowired
    private DictIntegration dictIntegration;
    @Autowired
    private ExcelIntegration excelIntegration;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private ExcelModelService excelModelService;
    @Autowired
    private ExcelCommonHelper excelCommonHelper;
    @Autowired
    private ExcelParamService excelParamService;


    @Override
    @OpApi(funcCode = "eduSchoolConfigJh0015", title = "义务教育学校招生计划管理员新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSchoolConfigJh0015",
            operationName = "义务教育学校配置表新增",
            dataType = "义务教育学校招生计划管理员新增",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void saveYwSchoolConfigInfo(SchoolConfigSaveVO vo) {
        if (ObjectUtils.isEmpty(vo.getEnrolment())){
            throw new AppException("招生人数不能为空！");
        }
        if (ObjectUtils.isEmpty(vo.getClassNum())){
            throw new AppException("班级数不能为空！");
        }
        int year = eduHelper.thisYear();
        if (!ObjectUtils.isEmpty(vo.getYear()) && vo.getYear() != year) {
            throw new AppException("不是当前年度数据不允许处理");
        }

        if (StringUtils.isBlank(vo.getSchoolId())) {
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }

        QueryWrapper<EduSchool> schoolQueryWrapper=new QueryWrapper<>();
        schoolQueryWrapper.lambda().eq(EduSchool::getOrgId,vo.getSchoolId())
                .eq(EduSchool::getStatus,BoolEnum.TRUE.getType())
                .eq(EduSchool::getRecruitStatus,BoolEnum.FALSE.getType());
        EduSchool eduSchool=eduSchoolService.getOne(schoolQueryWrapper,false);
        if(eduSchool==null){
            throw new AppException("学校不存在");
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduSchool.getAreaCode());
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("行政区划不能为空");
        }
        EduSchoolConfig config = Convert.convert(EduSchoolConfig.class, vo);
        config.setSchoolCategory(eduSchool.getSchoolCategory());
        config.setSchoolNature(eduSchool.getSchoolNature());
        QueryWrapper<EduSchoolConfig> schoolConfigNameQueryWrapper = new QueryWrapper<>();
        schoolConfigNameQueryWrapper
                .lambda()
                .eq(EduSchoolConfig::getYear, year)
                .eq(EduSchoolConfig::getConfigType, vo.getConfigType())
                .eq(EduSchoolConfig::getSchoolId, vo.getSchoolId())
                .ne(
                        StringUtils.isNotBlank(config.getSchoolConfigId()),
                        EduSchoolConfig::getSchoolConfigId,
                        config.getSchoolConfigId());
        long countName = eduSchoolConfigService.count(schoolConfigNameQueryWrapper);
        if (countName > 0) {
            throw new AppException("同一年度，同一类别重复");
        }
        if (config.getOrderNo() == null) {
            config.setOrderNo(Integer.parseInt(vo.getConfigType()));
        }
        QueryWrapper<EduSchoolConfig> orderNoQueryWrapper = new QueryWrapper<>();
        orderNoQueryWrapper
                .lambda()
                .eq(EduSchoolConfig::getYear, year)
                .eq(EduSchoolConfig::getOrderNo, config.getOrderNo())
                .eq(EduSchoolConfig::getSchoolId, vo.getSchoolId())
                .ne(
                        StringUtils.isNotBlank(config.getSchoolConfigId()),
                        EduSchoolConfig::getSchoolConfigId,
                        config.getSchoolConfigId());
        long countOrderNo = eduSchoolConfigService.count(orderNoQueryWrapper);
        if (countOrderNo > 0) {
            throw new AppException("同一年度，同一排序号重复");
        }
        if (StringUtils.isBlank(config.getSchoolConfigId())) {
            config.setSchoolConfigId(IdUtil.simpleUUID());
            config.setYear(year);
            if("0".equals(eduSchool.getSchoolNature())){
                //公办学校，只能配置一个
                QueryWrapper<EduSchoolConfig> countW = new QueryWrapper<>();
                countW.lambda()
                        .eq(EduSchoolConfig::getYear, year)
                        .eq(EduSchoolConfig::getSchoolId, vo.getSchoolId())
                        .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType());
                if( eduSchoolConfigService.count(countW)>0){
                    throw new AppException("公办学校只能配置一个类型的招生计划");
                }
            }
        }else{
            EduSchoolConfig oldSchoolConfig = eduSchoolConfigService.getById(config.getSchoolConfigId());
            if (AuthStatusEnum.NODO.getType().equals(oldSchoolConfig.getAuthStatus())){
                throw new AppException("审核中数据不允许修改");
            }
        }
       // EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class,vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if(eduOperationCacheVO.getOperation()==null){
            throw new AppException("招生计划参数未配置，请联系系统管理员");
        }
        if (vo.getSerialNumEnd() == null) {
            vo.setSerialNumEnd(0);
        }
        if (StringUtils.isBlank(vo.getFullFlag())) {
            vo.setFullFlag(BoolEnum.FALSE.getType());
        }
        config.setSchoolId(vo.getSchoolId());
        config.setStatus(vo.getStatus());
            config.setAuthStatus(BoolEnum.TRUE.getType());
            config.setAuthTime(new Date());
            config.setAuthRemarks("教育局管理员保存");
            config.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
        config.setStatus(BoolEnum.TRUE.getType());
        if (SchoolCategoryEnum.PRIMARY.getType().equalsIgnoreCase(config.getSchoolCategory())) {
            //小学
            if (eduOperationCacheVO.getOperation().get("YW005") == null) {
                throw new AppException("招生计划参数，小学允许就读出生日期未配置");
            }

            if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW005").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW005").getEndTime())){
                throw new AppException("招生计划参数“YW005” 未配置，请联系 "+ dictHelper.getAreaNameByCode(eduSchool.getAreaCode()) +" 管理员设置小学允许就读出生日期");
            }
            config.setStartAge(eduOperationCacheVO.getOperation().get("YW005").getBegTime());
            config.setEndAge(eduOperationCacheVO.getOperation().get("YW005").getEndTime());
        } else if (SchoolCategoryEnum.JUNIOR.getType().equalsIgnoreCase(config.getSchoolCategory())) {
            if (eduOperationCacheVO.getOperation().get("YW006") == null) {
                throw new AppException("招生计划参数，初中允许就读出生日期未配置");
            }
            if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW006").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW006").getEndTime())){
                throw new AppException("招生计划参数“YW006” 未配置，请联系 "+ dictHelper.getAreaNameByCode(eduSchool.getAreaCode()) +" 管理员设置初中允许就读出生日期");
            }
            config.setStartAge(eduOperationCacheVO.getOperation().get("YW006").getBegTime());
            config.setEndAge(eduOperationCacheVO.getOperation().get("YW006").getEndTime());
        }
        if (eduOperationCacheVO.getOperation().get("YW002") == null) {
            throw new AppException("招生计划参数，家长报名业务期未配置");
        }
        if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW002").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW002").getEndTime())){
            throw new AppException("招生计划参数“YW002” 未配置，请联系 "+dictHelper.getAreaNameByCode(eduSchool.getAreaCode())+" 管理员设置家长报名业务期");
        }
        config.setStartTime(eduOperationCacheVO.getOperation().get("YW002").getBegTime());
        config.setEndTime(DateUtil.parse(year + "0831"));
        config.setSerialNumEnd(vo.getSerialNumEnd());
        config.setFullFlag(vo.getFullFlag());
        eduSchoolConfigService.saveOrUpdate(config);
        eduSchoolService.clearCache(eduSchool.getOrgId(),eduSchool.getAreaCode());
    }



    @Override
    @OpApi(funcCode = "eduSchoolConfigJh0008", title = "招生计划模板下载（PC）", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void downloadModel(ExcelVO vo, HttpServletResponse response) {
        Map<String, List<SelectVO>> dictMap = new HashMap<>();
        dictMap.put("schoolName", getSchoolDictMap());
        dictMap.put("configType", getConfigTypeDictMap());
        vo.setDictMap(dictMap);
        excelIntegration.downloadModel(vo, response);
    }

    @Override
    @OpApi(funcCode = "eduSchoolConfigJh0007", title = "招生计划管理exceld导入（PC）", funcType = FuncTypeEnum.insert)
    public ExcelReadVO readExcel(ExcelVO vo, MultipartFile file) {
        String areaCode = "";
        if (SessionUtil.getSessionInfo() != null) {
            areaCode = SessionUtil.getAreaCode();
        }
        //判断是否在经办业务期内
        //eduHelper.checkOperation("2", "YW027", areaCode);
        ExcelReadVO excelReadVO = new ExcelReadVO();
        excelReadVO.setCount(0);
        ExcelModelVO excelModelVO = this.getModel(vo);
        InputStream in = null;
        try {
            in = file.getInputStream();
            List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);

            List<Map<String, Object>> successList = new ArrayList<>();
            List<Map<String, Object>> errorList = new ArrayList<>();
            List<String> idcardList = new ArrayList<>();
            EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
            queryVO.setAreaCode(SessionUtil.getAreaCode());
            queryVO.setClassify("2");
            EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryVO);
            int year = eduOperationCacheVO.getYear();
            for (Map<String, Object> map : list) {
                EduSchoolConfigVO schoolConfigVo = JSON.parseObject(JSON.toJSONString(map), EduSchoolConfigVO.class);
                QueryWrapper<EduSchool> schoolQueryWrapper = new QueryWrapper<>();
                schoolQueryWrapper.lambda().ne(EduSchool::getSchoolCategory, SchoolCategoryEnum.KINDERGARTEN.getType());
                List<EduSchool> schoolList = eduSchoolService.list(schoolQueryWrapper);
                String remarks = "";
                boolean flag = false;
                schoolConfigVo.setYear(year);
                //导入是中文情况下处理成数据字典
                if (StringUtils.isBlank(schoolConfigVo.getConfigType())) {
                    remarks += "选择招生类别不能为空！";
                    flag = true;
                }else {
                    DictQueryVO dictQueryVO = new DictQueryVO();
                    dictQueryVO.setDictField("YWCONFIGTYPE");
                    dictQueryVO.setDictValue(schoolConfigVo.getConfigType().trim());
                    String key = dictIntegration.getKey(dictQueryVO);
                    if (StringUtils.isBlank(key)) {
                        remarks += "招生类别类型数据格式不对！";
                        flag = true;
                    }
                    schoolConfigVo.setConfigTypeName(schoolConfigVo.getConfigType().trim());
                    schoolConfigVo.setConfigType(key);
                }
                if (ObjectUtils.isEmpty(schoolConfigVo.getEnrolment())){
                    remarks += "招生人数不能为空！";
                    flag = true;
                }
                if (schoolConfigVo.getEnrolment()<=0){
                    remarks += "招生人数不能小于或等于0！";
                    flag = true;
                }
                if (ObjectUtils.isEmpty(schoolConfigVo.getClassNum())){
                    remarks += "班级数不能为空！";
                    flag = true;
                }
                if (schoolConfigVo.getClassNum()<=0){
                    remarks +="班级数不能小于或等于0！";
                    flag = true;
                }
                /** 是否是直升班*/
                if (schoolConfigVo.getConfigType().equals("直升")){
                    schoolConfigVo.setZsFlag(BoolEnum.TRUE.getType());
                }
                AtomicBoolean schoolFlag = new AtomicBoolean(false);
                schoolList.forEach(
                        school -> {
                            if (!ObjectUtils.isEmpty(schoolConfigVo.getSchoolName())
                                    && school.getShortName()
                                    .replaceAll("（", "(")
                                    .replaceAll("）", ")")
                                    .equals(
                                            schoolConfigVo.getSchoolName()
                                                    .replaceAll("（", "(")
                                                    .replaceAll("）", ")"))) {
                                schoolFlag.set(true);
                                schoolConfigVo.setSchoolId(school.getOrgId());
                                schoolConfigVo.setShortName(school.getSchoolName());
                                schoolConfigVo.setSchoolNature(school.getSchoolNature());
                                schoolConfigVo.setSchoolCategory(school.getSchoolCategory());
                                schoolConfigVo.setOrderNo(school.getOrderBy());
                                schoolConfigVo.setAreaCode(school.getAreaCode());
                            }
                            if (ObjectUtils.isEmpty(schoolConfigVo.getSchoolId())){
                                if (!ObjectUtils.isEmpty(schoolConfigVo.getSchoolName())
                                        && school.getSchoolName()
                                        .replaceAll("（", "(")
                                        .replaceAll("）", ")")
                                        .equals(
                                                schoolConfigVo.getSchoolName()
                                                        .replaceAll("（", "(")
                                                        .replaceAll("）", ")"))) {
                                    schoolFlag.set(true);
                                    schoolConfigVo.setSchoolId(school.getOrgId());
                                    schoolConfigVo.setShortName(school.getSchoolName());
                                    schoolConfigVo.setSchoolNature(school.getSchoolNature());
                                    schoolConfigVo.setSchoolCategory(school.getSchoolCategory());
                                    schoolConfigVo.setOrderNo(school.getOrderBy());
                                }
                            }
                        });
                    if (!schoolFlag.get()) {
                        remarks += "找不到招生学校！";
                        flag = true;
                    }
                /** 同一学校同一学段同一类别不能多条*/
                QueryWrapper<EduSchoolConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("school_id",schoolConfigVo.getSchoolId())
                        .eq("config_type",schoolConfigVo.getConfigType())
                        .eq("school_category",schoolConfigVo.getSchoolCategory())
                        .eq("year",schoolConfigVo.getYear());
                List<EduSchoolConfig> eduSchoolConfigs = eduSchoolConfigService.list(queryWrapper);
                if (eduSchoolConfigs.size()>=1){
                    remarks +="同一年度同类别招生计划只能有一条！";
                    flag = true;
                }
                /**公办学校只能配置公办学校类别*/
                if (schoolConfigVo.getSchoolNature().equals(BoolEnum.FALSE.getType())){
                    if (!schoolConfigVo.getConfigTypeName().equals("公办")){
                            remarks +="公办学校只能配置公办学校类别！";
                            flag = true;
                    }
                }
                /**排序号*/
                schoolConfigVo.setOrderNo(Integer.parseInt(schoolConfigVo.getConfigType()));
                QueryWrapper<EduSchoolConfig> orderNoQueryWrapper = new QueryWrapper<>();
                orderNoQueryWrapper
                        .lambda()
                        .eq(EduSchoolConfig::getYear, year)
                        .eq(EduSchoolConfig::getOrderNo, schoolConfigVo.getOrderNo())
                        .eq(EduSchoolConfig::getSchoolId, schoolConfigVo.getSchoolId())
                        .ne(
                                StringUtils.isNotBlank(schoolConfigVo.getSchoolConfigId()),
                                EduSchoolConfig::getSchoolConfigId,
                                schoolConfigVo.getSchoolConfigId());
                long countOrderNo = eduSchoolConfigService.count(orderNoQueryWrapper);
                if (countOrderNo > 0) {
                    remarks +="同一年度，同一排序号重复！";
                    flag = true;
                }
                if (flag) {
                    schoolConfigVo.setRemarks(remarks);
                    errorList.add(JSON.parseObject(JSON.toJSONString(schoolConfigVo), Map.class));
                } else {
                    successList.add(JSON.parseObject(JSON.toJSONString(schoolConfigVo), Map.class));
                }
            }
            excelReadVO.setCount(successList.size() + errorList.size());
            excelReadVO.setSuccessCount(successList.size());
            excelReadVO.setSuccessList(successList);
            excelReadVO.setErrorList(errorList);
            excelReadVO.setErrorCount(errorList.size());
        } catch (AppException appEx) {
            throw appEx;
        } catch (IOException e) {
            throw new AppException("读取文件异常:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return excelReadVO;
    }

    @Override
    @OpApi(funcCode = "eduSchoolConfigJh0004", title = "招生计划管理excel导入保存（PC）", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSchoolConfigJh0004",
            operationName = "招生计划管理excel导入保存（PC）",
            dataType = "batch",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void addExcel(EduSchoolConfigExcelSaveVO vo) {
        if (CollectionUtils.isEmpty(vo.getEduSchoolConfigVOList())) {
            throw new AppException("没有传入需要保存的信息");
        }
        for (EduSchoolConfigVO saveVO : vo.getEduSchoolConfigVOList()) {
            EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
            queryVO.setAreaCode(saveVO.getAreaCode());
            queryVO.setClassify("2");
            EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryVO);
            Integer year = eduOperationCacheVO.getYear();
            //查询是否存在年度
            LambdaQueryWrapper<EduSchoolConfig> queryWrapper = new QueryWrapper<EduSchoolConfig>().lambda().eq(EduSchoolConfig::getSchoolId, saveVO.getSchoolId()).eq(EduSchoolConfig::getYear, year)
                    .eq(EduSchoolConfig::getConfigTypeName, saveVO.getConfigTypeName());
            if (eduSchoolConfigService.count(queryWrapper)>0){
                throw new AppException(saveVO.getSchoolName()+"招生计划已存在，不能重复添加");
            }
            saveVO.setAuthStatus(AuthStatusEnum.YES.getType());
            saveVO.setAuthRemarks("教育局管理员导入");
            saveVO.setStatus(BoolEnum.TRUE.getType());
            saveVO.setZsFlag(BoolEnum.FALSE.getType());
            saveVO.setFullFlag(BoolEnum.FALSE.getType());
            saveVO.setSerialNumEnd(0);
            saveVO.setYear(year);
            if (SchoolCategoryEnum.PRIMARY.getType().equalsIgnoreCase(saveVO.getSchoolCategory())) {
                //小学
                if (eduOperationCacheVO.getOperation().get("YW005") == null) {
                    throw new AppException("招生计划参数，小学允许就读出生日期未配置");
                }

                if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW005").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW005").getEndTime())){
                    throw new AppException("招生计划参数“YW005” 未配置，请联系 "+ dictHelper.getAreaNameByCode(saveVO.getAreaCode()) +" 管理员设置小学允许就读出生日期");
                }
                saveVO.setStartAge(eduOperationCacheVO.getOperation().get("YW005").getBegTime());
                saveVO.setEndAge(eduOperationCacheVO.getOperation().get("YW005").getEndTime());
            } else if (SchoolCategoryEnum.JUNIOR.getType().equalsIgnoreCase(saveVO.getSchoolCategory())) {
                if (eduOperationCacheVO.getOperation().get("YW006") == null) {
                    throw new AppException("招生计划参数，初中允许就读出生日期未配置");
                }
                if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW006").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW006").getEndTime())){
                    throw new AppException("招生计划参数“YW006” 未配置，请联系 "+ dictHelper.getAreaNameByCode(saveVO.getAreaCode()) +" 管理员设置初中允许就读出生日期");
                }
                saveVO.setStartAge(eduOperationCacheVO.getOperation().get("YW006").getBegTime());
                saveVO.setEndAge(eduOperationCacheVO.getOperation().get("YW006").getEndTime());
            }
            if (eduOperationCacheVO.getOperation().get("YW002") == null) {
                throw new AppException("招生计划参数，家长报名业务期未配置");
            }
            if (ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW002").getBegTime()) || ObjectUtils.isEmpty(eduOperationCacheVO.getOperation().get("YW002").getEndTime())){
                throw new AppException("招生计划参数“YW002” 未配置，请联系 "+dictHelper.getAreaNameByCode(saveVO.getAreaCode())+" 管理员设置家长报名业务期");
            }
            saveVO.setStartTime(eduOperationCacheVO.getOperation().get("YW002").getBegTime());
            saveVO.setEndTime(DateUtil.parse(year + "0831"));
            EduSchoolConfig eduSchoolConfig = Convert.convert(EduSchoolConfig.class, saveVO);
            eduSchoolConfigService.saveOrUpdate(eduSchoolConfig);
            eduSchoolService.clearCache(saveVO.getSchoolId(),saveVO.getAreaCode());
        }
    }

    @Override
    @OpApi(funcCode = "eduSchoolConfigJh0013", title = "招生计划错误数据下载", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void downloadErrorExcel(SchoolConfigFileVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        Map<String, List<SelectVO>> dictMap = new HashMap<>();
        dictMap.put("schoolName", getSchoolDictMap());
        dictMap.put("schoolNature", getSchoolNatureMap());
        dictMap.put("schoolCategory", getSchoolCategoryDictMap());
        dictMap.put("configType", getConfigTypeDictMap());
        excelVO.setDictMap(dictMap);

        ExcelModelVO excelModelVO = getModel(excelVO);
        String fileName = vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }

        EduSchoolVacancyQueryVO queryVO = new EduSchoolVacancyQueryVO();
        List<EduSchoolConfigVO> errorList1 = vo.getErrorList();
        for (EduSchoolConfigVO error : errorList1){
            error.setSchoolNature(error.getSchoolNatureName());
            error.setSchoolCategory(error.getSchoolCategoryName());
            error.setConfigType(error.getConfigTypeName());
        }
        List<Object> errorList = Convert.toList(Object.class, errorList1);

        excelCommonHelper.downloadExcelBean(excelModelVO, errorList, fileName, response);
    }

    public ExcelModelVO getModel(ExcelVO vo) {
        return this.getModel(vo.getModelCode(), vo.getExcelVersion(), vo.getDictMap());
    }
    public ExcelModelVO getModel(
            String modelCode, String version, Map<String, List<SelectVO>> dictMap) {
        if (StringUtils.isBlank(modelCode)) {
            throw new AppException("模板编号不能为空");
        }
        QueryWrapper<ExcelModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExcelModel::getModelCode, modelCode);
        if (StringUtils.isBlank(version)) {
            queryWrapper.lambda().eq(ExcelModel::getNewFlag, BoolEnum.TRUE.getType());
        } else {
            queryWrapper.lambda().eq(ExcelModel::getExcelVersion, version);
        }
        ExcelModel excelModel = excelModelService.getOne(queryWrapper, false);
        if (excelModel == null) {
            throw new AppException("未找到excel模板信息");
        }
        ExcelModelVO excelModelVO = Convert.convert(ExcelModelVO.class, excelModel);
        // 获取字段信息
        List<ExcelParamVO> paramVOList = this.getByModelId(excelModelVO.getId());
        for (ExcelParamVO excelParamVO : paramVOList) {
            if (excelParamVO.getHeaderBgColor() == null) {
                excelParamVO.setHeaderBgColor(excelModelVO.getHeaderBgColor());
            }
            if (excelParamVO.getHeaderColor() == null) {
                excelParamVO.setHeaderColor(excelModelVO.getHeaderColor());
            }
            if (excelParamVO.getBodyBgColor() == null) {
                excelParamVO.setBodyBgColor(excelModelVO.getBodyBgColor());
            }
            if (excelParamVO.getBodyColor() == null) {
                excelParamVO.setBodyColor(excelModelVO.getBodyColor());
            }
            if (StringUtils.isBlank(excelParamVO.getWrapText())) {
                excelParamVO.setWrapText(excelModelVO.getWrapText());
            }
            if (StringUtils.isBlank(excelParamVO.getFontName())) {
                excelParamVO.setFontName(excelModelVO.getFontName());
            }
            if (excelParamVO.getFontSize() == null) {
                excelParamVO.setFontSize(excelModelVO.getFontSize());
            }
            if (excelParamVO.getBorderSize() == null) {
                excelParamVO.setBorderSize(excelModelVO.getBorderSize());
            }
            if (excelParamVO.getBorderColor() == null) {
                excelParamVO.setBorderColor(excelModelVO.getBorderColor());
            }
            if (ExcelFieldVO.CellTypeEnum.SELECT.getType().equals(excelParamVO.getCellType())
                    || ExcelFieldVO.CellTypeEnum.MULTIPLESELECT
                    .getType()
                    .equals(excelParamVO.getCellType())) {
                String dictField = excelParamVO.getDictField();
                if (StringUtils.isBlank(dictField)) {
                    dictField = excelParamVO.getKey();
                }
                if (dictMap != null && dictMap.containsKey(dictField)) {
                    excelParamVO.setCodeList(dictMap.get(dictField));
                } else {
                    List<SelectVO> selectList = sysDictService.getDictByDictField(dictField);
                    excelParamVO.setCodeList(selectList);
                }
            }
        }
        excelModelVO.setParamVOList(paramVOList);
        if (StringUtils.isBlank(excelModelVO.getExcelType())) {
            excelModelVO.setExcelType(ExcelTypeEnum.xls.toString());
        }
        if (StringUtils.isBlank(excelModelVO.getExcelMode())) {
            excelModelVO.setExcelMode("2");
        }
        return excelModelVO;
    }
    public List<ExcelParamVO> getByModelId(String excelModelId) {
        QueryWrapper<ExcelParam> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ExcelParam::getExcelModelId, excelModelId)
                .orderByAsc(ExcelParam::getOrderNo)
                .orderByAsc(ExcelParam::getCreateTime);
        List<ExcelParam> list = excelParamService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<ExcelParamVO> voList = Convert.toList(ExcelParamVO.class, list);
        return voList;
    }
    private List<SelectVO> getConfigTypeDictMap() {
        DictQueryVO queryVO = new DictQueryVO();
        queryVO.setDictFields("YWCONFIGTYPE");
        Map<String, List<SelectVO>> dictBatch = dictIntegration.getDictBatch(queryVO);
        List<SelectVO> ywconfigtype = dictBatch.get("YWCONFIGTYPE");
        List<SelectVO> schoolDictList = new ArrayList<>();
        ywconfigtype.forEach(item -> {
            SelectVO selectVO = new SelectVO();
            selectVO.setDictKey(item.getDictKey());
            selectVO.setDictValue(item.getDictValue());
            selectVO.setDictField("configType");
            selectVO.setFieldName("招生类别");
            schoolDictList.add(selectVO);
        });
        return schoolDictList;
    }

    private List<SelectVO> getSchoolCategoryDictMap() {
        DictQueryVO queryVO = new DictQueryVO();
        queryVO.setDictFields("SCHOOLCATEGORY");
        Map<String, List<SelectVO>> dictBatch = dictIntegration.getDictBatch(queryVO);
        List<SelectVO> ywconfigtype = dictBatch.get("SCHOOLCATEGORY");
        List<SelectVO> schoolCategoryDictList = new ArrayList<>();
        ywconfigtype.forEach(item -> {
            SelectVO selectVO = new SelectVO();
            selectVO.setDictKey(item.getDictKey());
            selectVO.setDictValue(item.getDictValue());
            selectVO.setDictField("schoolCategory");
            selectVO.setFieldName("学段");
            schoolCategoryDictList.add(selectVO);
        });
        return schoolCategoryDictList;
    }

    private List<SelectVO> getSchoolNatureMap() {
        DictQueryVO queryVO = new DictQueryVO();
        queryVO.setDictFields("SCHOOLNATURE");
        Map<String, List<SelectVO>> dictBatch = dictIntegration.getDictBatch(queryVO);
        List<SelectVO> ywconfigtype = dictBatch.get("SCHOOLNATURE");
        List<SelectVO> schoolNatureDictList = new ArrayList<>();
        ywconfigtype.forEach(item -> {
            SelectVO selectVO = new SelectVO();
            selectVO.setDictKey(item.getDictKey());
            selectVO.setDictValue(item.getDictValue());
            selectVO.setDictField("schoolNature");
            selectVO.setFieldName("学校性质");
            schoolNatureDictList.add(selectVO);
        });
        return schoolNatureDictList;
    }

    private List<SelectVO> getSchoolDictMap() {
        String areaCode = SessionUtil.getAreaCode();
        LambdaQueryWrapper<EduSchool> queryWrapper = new QueryWrapper<EduSchool>()
                .lambda()
                .select(EduSchool::getOrgId, EduSchool::getShortName)
                .eq(EduSchool::getAreaCode,areaCode)
                .eq(EduSchool::getRecruitStatus, "0").ne(EduSchool::getSchoolCategory, "1");
        List<EduSchool> schoolList = eduSchoolService.list(queryWrapper);
        List<SelectVO> schoolDictList = new ArrayList<>();
        schoolList.forEach(
                item -> {
                    SelectVO selectVO = new SelectVO();
                    selectVO.setDictKey(item.getOrgId());
                    selectVO.setDictValue(item.getShortName());
                    selectVO.setDictField("schoolName");
                    selectVO.setFieldName("学校");
                    schoolDictList.add(selectVO);
                });
        return schoolDictList;
    }


}
